package Team

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_msg "sanguo/protocol/ss/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionCallTeammate struct {
	transaction.TransactionBase
	user *user.User
	req  *codecs.Message
}

func (this *transactionCallTeammate) GetModuleName() string {
	return "Team"
}

func (this *transactionCallTeammate) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionCallTeammate) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionCallTeammate) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionCallTeammate) Begin() {

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if nil == role || !role.IsRoleModleData() {
		node_game.Debugln(role.GetUserID(), "CallTeammate fail no selected role")
		this.user.EndTrans(this)
		return
	}

	_team := role.Team
	if _team == nil || !_team.TeamHeader {
		node_game.Infoln(role.GetUserID(), role.GetID(), "CallTeammate fail: _team is nil or not header")
		this.user.EndTrans(this)
		return
	}

	x, y, z := role.GetPos()
	req := &ss_msg.GameToTeam{
		MsgType: ss_msg.GTTType(ss_msg.GTTType_CallTeammate).Enum(),
		TeamID:  proto.Uint64(_team.TeamID),
		MapID:   proto.Int32(role.GetMapID()),
		PosX:    proto.Int32(x),
		PosY:    proto.Int32(y),
		PosZ:    proto.Int32(z),
	}

	cluster.PostMessage(node_game.GetTeamServer().ToPeerID(), req)

	this.user.EndTrans(this)
}

func (this *transactionCallTeammate) End() {
}

func (this *transactionCallTeammate) Timeout() {
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.CallTeammateToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionCallTeammate{
			user: user,
			req:  msg,
		}
	})
}
